package com.dbapp.shopping.controller;

import com.dbapp.shopping.data.GoodRepository;
import com.dbapp.shopping.data.UserRepository;
import com.dbapp.shopping.service.Service;
import com.dbapp.shopping.domain.Good;
import com.dbapp.shopping.domain.User;
import com.dbapp.shopping.storage.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.multipart.MultipartFile;

import java.util.Optional;



@Controller
@RequestMapping
public class EditController {

    private PasswordEncoder passwordEncoder;
    private StorageService storageService;
    private Service service;

    @Autowired
    public EditController(PasswordEncoder passwordEncoder, StorageService storageService,
                          Service service)
    {
        this.passwordEncoder = passwordEncoder;
        this.storageService = storageService;
        this.service = service;
    }

    @GetMapping("/edit-goods={id}")
    public String getEditGoods(Model model, @PathVariable("id") Long id, @AuthenticationPrincipal User user)
    {
        model.addAttribute("user", user)
                .addAttribute("status", true)
                .addAttribute("get", true)
                .addAttribute("checkeditgoodsname", true)
                .addAttribute("checkeditgoodsdescription", true)
                .addAttribute("checkeditgoodsstock", true)
                .addAttribute("checkeditgoodsprice", true)
                .addAttribute("checkeditgoodsimg", true);
        Optional<Good> good = service.getGoodById(id);
        if(good.isPresent()) {
            model.addAttribute("editgoods", good.get());
            return "/edit-goods";
        }
        else
            return "error";
    }

    @PostMapping("/edit-goods")
    public String processEditGoods(Model model, Long id, String name, String description,
                                   String price, String stock, @AuthenticationPrincipal User user,
                                   @RequestParam("avataruri") MultipartFile img)
    {
        model.addAttribute("user", user)
                .addAttribute("status", true)
                .addAttribute("get", false)
                .addAttribute("checkeditgoodsname", true)
                .addAttribute("checkeditgoodsdescription", true)
                .addAttribute("checkeditgoodsstock", true)
                .addAttribute("checkeditgoodsprice", true)
                .addAttribute("checkeditgoodsimg", true);
        Optional<Good> good = service.getGoodById(id);
        String extension = StringUtils.getFilenameExtension(img.getOriginalFilename());
        if(good.isPresent()) {
            Good g = good.get();
            Boolean flag = false;
            if(!img.isEmpty() && !(extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png")))
            {
                model.addAttribute("checkeditgoodsimg", false);
                flag = true;
            }
            if(name.isEmpty())
            {
                model.addAttribute("checkeditgoodsname", false);
                flag = true;
            }
            if(description.isEmpty())
            {
                model.addAttribute("checkeditgoodsdescription", false);
                flag = true;
            }
            if(stock.isEmpty() || !service.isStock(stock))
            {
                model.addAttribute("checkeditgoodsstock", false);
                flag = true;
            }
            if(price.isEmpty() || !service.isPrice(price))
            {
                model.addAttribute("checkeditgoodsprice", false);
                flag = true;
            }
            if(flag)
            {
                model.addAttribute("editgoods", g);
                return "/edit-goods";
            }
            g.setName(name);
            g.setDescription(description);
            g.setPrice(Double.valueOf(price));
            g.setStock(Long.valueOf(stock));
            if(!img.isEmpty())
            {
                String newName = id.toString() + "." + extension;
                storageService.storeGoodsImg(img, newName);
                g.setAvataruri("/PJImg/goodsImg/" + newName);
            }
            service.saveGood(g);
            return "redirect:/goods=" + g.getId().toString();
        }
        else
            return "error";
    }

    @GetMapping("/edit-profile")
    public String getEditProfile(Model model, @AuthenticationPrincipal User user)
    {
        model.addAttribute("user", user)
                .addAttribute("status", true)
                .addAttribute("get", true)
                .addAttribute("passwordcheck", true)
                .addAttribute("imgcheck", true);
        return "/edit-profile";
    }

    @PostMapping("/edit-profile")
    public String processEditProfile(Model model, @AuthenticationPrincipal User user,
                                     String oldpassword, String newpassword, String name,
                                     Character sex, @RequestParam("avataruri") MultipartFile img)
    {
        model.addAttribute("user", user)
                .addAttribute("status", true)
                .addAttribute("get", false)
                .addAttribute("passwordcheck", true)
                .addAttribute("imgcheck", true);
        String extension = StringUtils.getFilenameExtension(img.getOriginalFilename());
        if(!passwordEncoder.matches(oldpassword, user.getPassword()))
        {
            model.addAttribute("passwordcheck", false);
            return "/edit-profile";
        }
        if(!img.isEmpty() && !(extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png")))
        {
            model.addAttribute("imgcheck", false);
            return "/edit-profile";
        }
        if(!newpassword.isEmpty())
            user.setPassword(passwordEncoder.encode(newpassword));
        if(!img.isEmpty())
        {
            String newName = user.getId().toString() + "." + extension;
            storageService.storeUserImg(img, newName);
            user.setAvataruri("/PJImg/userImg/" + newName);
        }
        user.setSex(sex);
        user.setName(name);
        service.saveUser(user);
        model.addAttribute("user", user);
        return "redirect:/profile=" + user.getUsername();
    }
}
